package com.hellogood.work.evaluate.server.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hellogood.work.evaluate.server.db.DBHelper;
import com.hellogood.work.evaluate.shared.exception.DatabaseException;
import com.hellogood.work.evaluate.shared.po.User;

public class UserDAO extends DBHelper {

	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<User> list = new ArrayList<User>();
		if (rs != null) {
			while (rs.next()) {
				User user = new User();
				Object usercode = rs.getString("usercode");
				Object username = rs.getString("username"); 
				user.setUsercode(usercode == null ? "" : usercode.toString().trim());
				user.setUsername(username == null ? "" : username.toString().trim());				
				list.add(user);
			}
		}
		return list;
	}

	public User login(String usercode, String password) {
		String sql = "SELECT * FROM HGUser WHERE usercode = '" + usercode + "' and password = '" + password + "';";
		List<?> list = super.query(sql);
		if (list.isEmpty()) {
			return null;
		}
		return (User) list.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<User> getList() {
		String sql = "SELECT * FROM HGUser ORDER BY usercode";
		List<?> list = super.query(sql);
		return (List<User>) list;
	}

	public int getTotalNumber() {
		String sql = "SELECT COUNT(*) AS totalNumber FROM HGUser";
		return super.getTotalNumber(sql);
	}

	public String modify(User user, boolean isModiy) {
		String sql = "INSERT INTO HGUser(UserCode,UserName,PassWord) VALUES('" + user.getUsercode() + "','" + user.getUsername() + "','" + user.getPassword() + "')";
		if (isModiy) {
			sql = "UPDATE HGUser SET UserName = '" + user.getUsername() + "',PassWord = '" + user.getPassword() + "' WHERE UserCode = '" + user.getUsercode() + "'";
		}
		try {
			if (super.execute(sql) > 0) {
				return "";
			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			return "执行新建、修改用户信息错误";
		}
		return "执行新建、修改用户信息错误";
	}

	public String getMaxCode() {
		String sql = "SELECT MAX(usercode) AS maxcode FROM HGUser";
		return super.getMaxCode(sql, "maxcode");
	}
}
